package xcache

import (
	"encoding/json"
	"errors"
	"fmt"
	"strings"
	"time"
)

// 读取缓存信息
func Get[T CacheKey | string](key T) string {
	k := string(key)
	if !strings.Contains(k, ":") {
		// 剔除:及前面的字符
		k = defaultGroup + ":" + k
	}
	if v, ok := cacheSync.Load(k); ok {
		if typ, ok := v.(cacheData); ok {
			if typ.Expire > 0 && time.Now().Unix() < typ.Expire {
				return typ.Value
			} else {
				Remove(k)
			}
		}
	}
	// 读取外部缓存
	for i := 0; i < len(cacheLevel); i++ {
		if v, err := cacheLevel[i].Load(k); err == nil && v != "" {
			// 解析v的值
			typ := cacheData{}
			json.Unmarshal([]byte(v), &typ)
			if typ.Expire > 0 && time.Now().Unix() < typ.Expire {
				return typ.Value
			} else {
				cacheLevel[i].Delete(k)
			}
		}
	}
	return ""
}

// 获取结构体缓存
//
//	key		缓存key
//	value	结构体指针
func GetStruct[T CacheKey | string](key T, value any) error {
	v := Get(key)
	if v == "" {
		return errors.New("缓存已过期")
	}
	err := json.Unmarshal([]byte(v), value)
	if err != nil {
		if v != "" && v[0] != '"' {
			return json.Unmarshal([]byte(fmt.Sprintf("\"%s\"", v)), value)
		} else {
			return err
		}
	}
	return nil
}
